#coding=utf-8
import numpy as np
import sys
import time
import socket
import Gesture.Leap as Leap
import Gesture.mul_svm as mul_svm
import Gesture.read as read
import Gesture.rotation as rotation


"""
svm训练
"""
def SVM_train(train_path):
    y, X, direct = read.data_read(train_path)
    direct = np.reshape(direct, (len(direct), 1, 3))
    X = rotation.deal_Rotation(X)
    X = np.column_stack((X, direct))
    X = np.array(X)
    X = np.reshape(X, (len(X), 63))
    y = np.array(y)
    clf = mul_svm.train(X, y)
    return clf


class SampleListener(Leap.Listener):
    def __init__(self,clf,gui):
        super(SampleListener,self).__init__()
        self._clf=clf
        self._gui=gui
        self._instructions = ['up', 'down', 'right', '', 'left', '开始']

    def on_init(self, controller):  # 初始化
        print("Initialized")

    def on_connect(self, controller):   # 连接
        print("Connected")

    def on_disconnect(self, controller):    # 连接失败
        print("Disconnected")

    def on_exit(self, controller):  # 退出
        print("Exited")

    def on_frame(self, controller): # 运行过程
        time.sleep(0.1)
        frame = controller.frame(20)
        bone_list = []
        direction = []
        for hand in list(frame.hands):
            if hand.is_right:   # 判断是否右手
                print('It is right hand!,not left hand')
                break
            else:
                for finger in list(hand.fingers):
                    for b in range(0, 4):
                        bone = finger.bone(b)
                        bone_list.append([float(i) for i in str(bone.next_joint).replace('(', "").replace(')', "").split(",")])
                bone_list = np.array(bone_list)
                n = np.array([bone_list[5]-bone_list[7]])[0]
                direction = [i >= 0 for i in n]
                bone_list = rotation.deal_Rotation([bone_list])
                bone_list = np.array(bone_list).reshape(20,3)
                bone_list = np.vstack((bone_list,n))

        if len(bone_list) != 0:
            bone_list = np.reshape(bone_list, (-1, 63))
            y = self._clf.predict(bone_list)[0]
            prob = np.max(self._clf._predict_proba_lr(bone_list))
            if y == 1:
                if direction[0] == True:
                    y = 4

            if self._gui.flag == 4:
                self._gui.outputAllPredictWord(self._instructions[int(y)], prob, 3)
            else:
                self._gui.outputPredictWord(self._instructions[int(y)])

        if not self._gui.is_run:
            self._gui.outputPredictWord("")
            return

"""
LeapMotion预测类，用于运行手势的判断
"""
class LeapMotionPredictionMoel():
    def __init__(self,svm_train_path):
        self._clf=SVM_train(svm_train_path)
        self.controller = Leap.Controller()

    def run(self,gui):
        listener = SampleListener(self._clf,gui)
        self.controller.add_listener(listener)
        try:
            sys.stdin.readline()
        except KeyboardInterrupt:
            pass
        finally:
            # Remove the sample listener when done
            self.controller.remove_listener(listener)